package com.pyq;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteCallbackList;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import cn.jpush.android.ui.h;

import com.adpter.PyqAdapter;
import com.app.DemoApplication;
import com.common.method.ServerPath;
import com.contact.BaseActivity;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.http.NetCallBack;
import com.http.PyqListTask;
import com.http.RemovePyqTask;
import com.http.UserInfoTask;
import com.interfacem.UpdateCallBack;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.matang.R;
import com.modle.PyqUser;
import com.modle.User;
import com.util.AppUtil;
import com.util.UpCallback;
import com.util.UserUtil;
import com.view.NonScrollListView;

public class PyqMainFragment extends Fragment implements UserInfoTask.CallBack{

	private PyqAdapter adapter;
	List<PyqUser> pyqUsers;
	private TextView tvUserName;
	private ImageView imgHead;
	private BitmapUtils bitmapUtils;
	private View view;
	private ImageView imgTake;
	private ImageView imgBack;
	private PullToRefreshScrollView mPullRefreshScrollView;
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.pyq_main, container,false);
		init();
	
		return view;
	}
	@Override
	public void onResume() {
		loadUserData();
		LoadData();
		super.onResume();
	}
	private void init() {
	
	//	LoadData();
		findView();
	
		setData();
		imgTake.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(getActivity(), SlectResultActivity.class);
				startActivity(intent);
				
			}
		});
		imgBack = (ImageView)view.findViewById(R.id.img_back);
		imgBack.setOnClickListener(new OnClickListener() {
			
		
			public void onClick(View v) {
				
				getActivity().finish();
			}
		});
	//	initPaneData();
	}
	public Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			Log.i("test", "刷新朋友圈");
			isXl = true;
			LoadData();
		};
	};
	private void loadUserData() {
	
		User user = UserUtil.readUser();
		if(user == null){
			AppUtil.tsMsg(getActivity(), "请先登录");
			return;
		}else {
			new UserInfoTask(this).execute(user.id);
		}
		
	}

	private int currentPage = 1;
	private void LoadData() {
		User user = UserUtil.readUser();
		if(user == null){
			AppUtil.tsMsg(getActivity(), "请先登录");
			return;
		}else {
			new PyqListTask(callBack).execute(user.id,currentPage+"");
		}
	
		
	}
//	protected void onRestart() {
//		super.onRestart();
//		isXl = true;
//		currentPage = 1 ;
//		LoadData();
//	};
	NetCallBack callBack = new NetCallBack() {
		public void onSuccess(Object... obj) {
			mPullRefreshScrollView.onRefreshComplete();
			Log.i("test", obj.toString());
			List<PyqUser> datas = (List<PyqUser>) obj[0];
		
			if (datas == null) {
				adapter.clearData();
				AppUtil.tsMsg(getActivity(), "没有数据");
				return;
			}
			if (isXl) {
				adapter.clearData();
			}
			if (datas != null) {
				adapter.addData(datas);
			}
			if (datas.size()<10) {
				//pullToRefreshListView.setMode(Mode.PULL_FROM_START);
			}else {
				//pullToRefreshListView.setMode(Mode.BOTH);
			}
		
		}

	
		public void onError(Object... obj) {
		
		
		}
	};
	private boolean isXl = false;
	private NonScrollListView pullToRefreshListView = null;
	class MyOnRefreshListener2 implements OnRefreshListener2<ListView> {

		private PullToRefreshListView mPtflv;

		public MyOnRefreshListener2(PullToRefreshListView ptflv) {
			this.mPtflv = ptflv;

		}

		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
			// 下拉刷新
			String mLabel = DateUtils.formatDateTime(
					getActivity(),
					System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
					| DateUtils.FORMAT_SHOW_DATE
					| DateUtils.FORMAT_ABBREV_ALL);

			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(mLabel);
			isXl = true;
			currentPage= 1;
			LoadData();

		}

		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
			// 上拉加载
			isXl = false;
			currentPage++;
			LoadData();
		
		}

	}
//	public void initPaneData() {
//		
//		header.headRightTv.setBackgroundResource(R.drawable.take_camera);
//		
//		header.headTitleTv.setText("朋友圈");
//		header.headLeftTv.setVisibility(View.VISIBLE);
//		header.headRightTv.setVisibility(View.VISIBLE);
//		//header.headRightTv.setText("添加");
//		header.headRightTv.setOnClickListener(new OnClickListener() {
//			
//		
//			public void onClick(View view) {
//				Intent intent = new Intent();
//				intent.setClass(getActivity(), SlectResultActivity.class);
//				startActivity(intent);
//				
//			}
//		});
//		header.headLeftTv.setOnClickListener(new OnClickListener() {
//			
//	
//			public void onClick(View arg0) {
//				PyqMainActivity.this.finish();
//			}
//		});
//	
//
//	}

	private void setData() {
		if (adapter == null) {
			adapter = new PyqAdapter(getActivity());
		}
		pullToRefreshListView.setAdapter(adapter);
		
		pullToRefreshListView.setOnItemClickListener(new OnItemClickListener() {

		
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				PyqUser pyqUser = (PyqUser) arg0.getAdapter().getItem(arg2);
				User user = UserUtil.readUser();
				if (user.id.equals(pyqUser.getUserId())) {
					showTs(pyqUser);
				}else {
					Toast.makeText(getActivity(), "您没有权限删除其他人的消息", 0).show();
				}
			
				
			}
		});
	}
	
	private void showTs(final PyqUser pyqUser){
		new AlertDialog.Builder(getActivity()).setTitle("删除").setMessage("确认删除该条记录?")
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				removePyq(pyqUser.getId());
				arg0.dismiss();
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
		
			public void onClick(DialogInterface arg0, int arg1) {
				arg0.dismiss();
				
			}
		}).show();
	}

	private void findView() {
		imgTake = (ImageView) view.findViewById(R.id.img_take);
		tvUserName = (TextView) view.findViewById(R.id.tv_username);
		imgHead = (ImageView) view.findViewById(R.id.img_yh);
		pullToRefreshListView = (NonScrollListView) view.findViewById(R.id.audio_list);
	//	pullToRefreshListView.setMode(Mode.BOTH);
		mPullRefreshScrollView = (PullToRefreshScrollView) view.findViewById(R.id.pull_refresh_scrollview);
//		pullToRefreshListView.setOnRefreshListener(new MyOnRefreshListener2(
//				pullToRefreshListView));
		if (bitmapUtils == null) {
			bitmapUtils = new BitmapUtils(getActivity());
		}
		//findViews();
	
		 mPullRefreshScrollView.getLoadingLayoutProxy().setLastUpdatedLabel("lastUpdateLabel");   
	        mPullRefreshScrollView.getLoadingLayoutProxy().setPullLabel("PULLLABLE");  
	        mPullRefreshScrollView.getLoadingLayoutProxy().setRefreshingLabel("refreshingLabel");  
	        mPullRefreshScrollView.getLoadingLayoutProxy().setReleaseLabel("releaseLabel");  
	          
	        //上拉、下拉设定  
	        mPullRefreshScrollView.setMode(Mode.PULL_FROM_START);  
	          
	        //上拉监听函数  
	        mPullRefreshScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {  
	              
	            @Override  
	            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {  
	                //执行刷新函数  
	            	isXl = true;
	    			currentPage= 1;
	    			LoadData();
	            }  
	        });  
	  
	        //获取ScrollView布局，此文中用不到  
	     
	    
	  
	}

	public void onClick(View arg0) {
	
		
	}
	
	private void removePyq(String mid){
		HashMap<String, Object> mymap = new LinkedHashMap<String, Object>();
		mymap.put("mid", mid);
		new RemovePyqTask(new RemovePyqTask.CallBack() {
			
			@Override
			public void procError(String msg) {
				
				
				AppUtil.tsMsg(getActivity(), "删除记录失败");
			}
			

			public void removePyq(String result) {
			
				AppUtil.tsMsg(getActivity(), "删除记录成功");
				isXl = true;
				currentPage= 1;
				LoadData();

				
			}
		}).execute(mymap);
	}

	@Override
	public void procError(String msg) {
		// TODO Auto-generated method stub
		
	}

	public void procUserInfoData(User data) {
		String thumb = ServerPath.SERVER+data.thumb;
		String name = data.nickName;
		tvUserName.setText(name);
		bitmapUtils.display(imgHead, thumb, new BitmapLoadCallBack<View>() {

			@Override
			public void onLoadCompleted(View container, String uri,
					Bitmap bitmap, BitmapDisplayConfig config,
					BitmapLoadFrom from) {
				((ImageView)container).setImageBitmap(AppUtil.getRoundedCornerBitmap(bitmap));
				
			}

			@Override
			public void onLoadFailed(View container, String uri,
					Drawable drawable) {
				((ImageView)container).setImageResource(R.drawable.default_avatar);
				
			}
		});
		
	}

	@Override
	public void procUserInfoError(String msg) {
		// TODO Auto-generated method stub
		
	}
	

}
